<template>
  <!-- 内联样式绑定引入的背景图，确保路径解析无误 -->
  <div class="login-container" :style="{ backgroundImage: `url(${bgImg})` }">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>

      <form @submit.prevent="handleLogin" class="login-form" novalidate>
        <div class="form-group">
          <label for="phone">手机号</label>
          <input
            type="tel"
            id="phone"
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            required
            @input="validatePhone"
            @blur="validatePhone"
          />
          <p v-if="phoneError" class="error-message">{{ phoneError }}</p>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <div class="password-input">
            <input
              :type="showPassword ? 'text' : 'password'"
              id="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              required
              @input="validatePassword"
              @blur="validatePassword"
            />
            <button
              type="button"
              class="toggle-password"
              @click.prevent="showPassword = !showPassword"
            >
              {{ showPassword ? "隐藏" : "显示" }}
            </button>
          </div>
          <p v-if="passwordError" class="error-message">{{ passwordError }}</p>
        </div>

        <div class="form-actions">
          <button
            type="submit"
            class="login-btn"
            :disabled="isSubmitting || !isFormValid"
          >
            <span v-if="!isSubmitting">登录</span>
            <span v-else>登录中...</span>
          </button>
        </div>
      </form>

      <p v-if="loginError" class="login-error">{{ loginError }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
// 关键：引入 assets 目录下的背景图，@ 是 src 目录的别名
import bgImg from "@/assets/background.jpg";

import { inMemoryStorage } from "/src/router/index.js";

// axios配置
axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.withCredentials = true;

// 路由实例
const router = useRouter();

// 登录表单数据
const loginForm = reactive({
  phone: "",
  password: "",
});

// 状态管理
const showPassword = ref(false);
const isSubmitting = ref(false);
const loginError = ref("");
const phoneError = ref("");
const passwordError = ref("");

// 手机号验证
const validatePhone = () => {
  if (!loginForm.phone.trim()) {
    phoneError.value = "手机号不能为空";
  } else if (!/^\d{11}$/.test(loginForm.phone.trim())) {
    phoneError.value = "请输入11位手机号";
  } else {
    phoneError.value = "";
  }
};

// 密码验证
const validatePassword = () => {
  if (!loginForm.password.trim()) {
    passwordError.value = "密码不能为空";
  } else if (loginForm.password.length < 6) {
    passwordError.value = "密码长度不能少于6位";
  } else {
    passwordError.value = "";
  }
};

// 表单是否有效
const isFormValid = computed(() => {
  return (
    !phoneError.value &&
    !passwordError.value &&
    loginForm.phone.trim() &&
    loginForm.password.trim()
  );
});

// 处理登录（支持管理员和工人角色）
const handleLogin = async () => {
  validatePhone();
  validatePassword();

  if (!isFormValid.value) {
    return;
  }

  try {
    isSubmitting.value = true;
    loginError.value = "";

    const response = await axios.post("/auth/login", loginForm);

    // 登录成功（后端返回token和role）
    if (response.data.token && response.data.role) {
      // 保存token和角色信息
      inMemoryStorage.token = response.data.token;
      inMemoryStorage.role = response.data.role;

      // 根据角色跳转到对应页面
      if (response.data.role === "Administrator") {
        await router.replace("/admin"); // 管理员跳管理员首页
      } else if (response.data.role === "Worker") {
        await router.replace("/admin/pond"); // 工人跳工人首页
      } else {
        loginError.value = "未知角色，无法登录";
        // 清除无效角色的登录状态
        inMemoryStorage.token = "";
        inMemoryStorage.role = "";
      }
    } else if (response.data.code === 401) {
      loginError.value = response.data.message || "账号或密码错误";
    } else {
      loginError.value = "登录异常，请稍后重试";
    }
  } catch (error) {
    console.error("登录请求失败:", error);
    if (error.response) {
      if (error.response.status === 404) {
        loginError.value = "接口未找到，请检查服务是否启动";
      } else if (error.response.status === 500) {
        loginError.value = "服务器内部错误，请稍后重试";
      } else {
        loginError.value = `请求失败（${error.response.status}）`;
      }
    } else if (error.request) {
      loginError.value = "无法连接到服务器，请检查网络或服务状态";
    } else {
      loginError.value = "登录失败：" + error.message;
    }
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-size: cover; /* 背景图全屏覆盖 */
  background-position: center; /* 背景图居中 */
  background-repeat: no-repeat; /* 背景图不重复 */
  /* 半透明白色遮罩，避免背景过亮导致表单看不清 */
  background-color: rgba(255, 255, 255, 0.1);
  background-blend-mode: overlay;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: rgba(255, 255, 255, 0.8); /* 卡片轻微透明，融合背景 */
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.login-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.form-group input {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #409eff;
}

.password-input {
  display: flex;
}

.password-input input {
  flex: 1;
  border-right: none;
  border-radius: 6px 0 0 6px;
}

.toggle-password {
  padding: 0 15px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-left: none;
  border-radius: 0 6px 6px 0;
  color: #666;
  cursor: pointer;
  transition: background-color 0.3s;
}

.toggle-password:hover {
  background-color: #eee;
}

.form-actions {
  margin-top: 10px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover:not(:disabled) {
  background-color: #66b1ff;
}

.login-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.error-message,
.login-error {
  color: #f56c6c;
  font-size: 14px;
  margin: 0;
}

.login-error {
  margin-top: 15px;
  text-align: center;
  min-height: 20px;
}
</style>
